{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "b3b5a600",
   "metadata": {},
   "source": [
    "# GraphFlow (Workflows)\n",
    "\n",
    "In this section you'll learn how to create an _multi-agent workflow_ using {py:class}`~autogen_agentchat.teams.GraphFlow`, or simply \"flow\" for short.\n",
    "It uses structured execution and precisely controls how agents interact to accomplish a task.\n",
    "\n",
    "We'll first show you how to create and run a flow. We'll then explain how to observe and debug flow behavior, \n",
    "and discuss important operations for managing execution.\n",
    "\n",
    "AutoGen AgentChat provides a team for directed graph execution:\n",
    "\n",
    "- {py:class}`~autogen_agentchat.teams.GraphFlow`: A team that follows a {py:class}`~autogen_agentchat.teams.DiGraph`\n",
    "to control the execution flow between agents. \n",
    "Supports sequential, parallel, conditional, and looping behaviors.\n",
    "\n",
    "```{note}\n",
    "**When should you use {py:class}`~autogen_agentchat.teams.GraphFlow`?**\n",
    "\n",
    "Use Graph when you need strict control over the order in which agents act, or when different outcomes must lead to different next steps.\n",
    "Start with a simple team such as {py:class}`~autogen_agentchat.teams.RoundRobinGroupChat` or {py:class}`~autogen_agentchat.teams.SelectorGroupChat`\n",
    "if ad-hoc conversation flow is sufficient. \n",
    "Transition to a structured workflow when your task requires deterministic control,\n",
    "conditional branching, or handling complex multi-step processes with cycles.\n",
    "```\n",
    "\n",
    "> **Warning:** {py:class}`~autogen_agentchat.teams.GraphFlow` is an **experimental feature**. \n",
    "Its API, behavior, and capabilities are **subject to change** in future releases."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f04e4271",
   "metadata": {},
   "source": [
    "## Creating and Running a Flow\n",
    "\n",
    "{py:class}`~autogen_agentchat.teams.DiGraphBuilder` is a fluent utility that lets you easily construct execution graphs for workflows. It supports building:\n",
    "\n",
    "- Sequential chains\n",
    "- Parallel fan-outs\n",
    "- Conditional branching\n",
    "- Loops with safe exit conditions\n",
    "\n",
    "Each node in the graph represents an agent, and edges define the allowed execution paths. Edges can optionally have conditions based on agent messages."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "760ee783",
   "metadata": {},
   "source": [
    "### Sequential Flow\n",
    "\n",
    "We will begin by creating a simple workflow where a **writer** drafts a paragraph and a **reviewer** provides feedback. This graph terminates after the reviewer comments on the writer. \n",
    "\n",
    "Note, the flow automatically computes all the source and leaf nodes of the graph and the execution starts at all the source nodes in the graph and completes execution when no nodes are left to execute."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "c6dd0386",
   "metadata": {},
   "outputs": [],
   "source": [
    "from autogen_agentchat.agents import AssistantAgent\n",
    "from autogen_agentchat.teams import DiGraphBuilder, GraphFlow\n",
    "from autogen_ext.models.openai import OpenAIChatCompletionClient\n",
    "\n",
    "# Create an OpenAI model client\n",
    "client = OpenAIChatCompletionClient(model=\"gpt-4.1-nano\")\n",
    "\n",
    "# Create the writer agent\n",
    "writer = AssistantAgent(\"writer\", model_client=client, system_message=\"Draft a short paragraph on climate change.\")\n",
    "\n",
    "# Create the reviewer agent\n",
    "reviewer = AssistantAgent(\"reviewer\", model_client=client, system_message=\"Review the draft and suggest improvements.\")\n",
    "\n",
    "# Build the graph\n",
    "builder = DiGraphBuilder()\n",
    "builder.add_node(writer).add_node(reviewer)\n",
    "builder.add_edge(writer, reviewer)\n",
    "\n",
    "# Build and validate the graph\n",
    "graph = builder.build()\n",
    "\n",
    "# Create the flow\n",
    "flow = GraphFlow([writer, reviewer], graph=graph)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1b19f9a6",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "source='user' models_usage=None metadata={} content='Write a short paragraph about climate change.' type='TextMessage'\n",
      "source='writer' models_usage=RequestUsage(prompt_tokens=28, completion_tokens=95) metadata={} content='Climate change refers to long-term shifts in temperature, precipitation, and other atmospheric patterns, largely driven by human activities such as burning fossil fuels, deforestation, and industrial processes. These changes contribute to rising global temperatures, melting ice caps, more frequent and severe weather events, and adverse impacts on ecosystems and human communities. Addressing climate change requires global cooperation to reduce greenhouse gas emissions, transition to renewable energy sources, and implement sustainable practices to protect the planet for future generations.' type='TextMessage'\n",
      "source='reviewer' models_usage=RequestUsage(prompt_tokens=127, completion_tokens=144) metadata={} content=\"The paragraph provides a clear overview of climate change, its causes, and its impacts. To enhance clarity and engagement, consider adding specific examples or emphasizing the urgency of action. Here's a revised version:\\n\\nClimate change is a long-term alteration of Earth's climate patterns caused primarily by human activities such as burning fossil fuels, deforestation, and industrial emissions. These actions increase greenhouse gases in the atmosphere, leading to rising global temperatures, melting ice caps, and more frequent extreme weather events like hurricanes and droughts. The effects threaten ecosystems, disrupt agriculture, and endanger communities worldwide. Addressing this crisis requires urgent, coordinated global efforts to reduce emissions, adopt renewable energy, and promote sustainable practices to safeguard the planet for future generations.\" type='TextMessage'\n",
      "source='DiGraphStopAgent' models_usage=None metadata={} content='Digraph execution is complete' type='StopMessage'\n",
      "messages=[TextMessage(source='user', models_usage=None, metadata={}, content='Write a short paragraph about climate change.', type='TextMessage'), TextMessage(source='writer', models_usage=RequestUsage(prompt_tokens=28, completion_tokens=95), metadata={}, content='Climate change refers to long-term shifts in temperature, precipitation, and other atmospheric patterns, largely driven by human activities such as burning fossil fuels, deforestation, and industrial processes. These changes contribute to rising global temperatures, melting ice caps, more frequent and severe weather events, and adverse impacts on ecosystems and human communities. Addressing climate change requires global cooperation to reduce greenhouse gas emissions, transition to renewable energy sources, and implement sustainable practices to protect the planet for future generations.', type='TextMessage'), TextMessage(source='reviewer', models_usage=RequestUsage(prompt_tokens=127, completion_tokens=144), metadata={}, content=\"The paragraph provides a clear overview of climate change, its causes, and its impacts. To enhance clarity and engagement, consider adding specific examples or emphasizing the urgency of action. Here's a revised version:\\n\\nClimate change is a long-term alteration of Earth's climate patterns caused primarily by human activities such as burning fossil fuels, deforestation, and industrial emissions. These actions increase greenhouse gases in the atmosphere, leading to rising global temperatures, melting ice caps, and more frequent extreme weather events like hurricanes and droughts. The effects threaten ecosystems, disrupt agriculture, and endanger communities worldwide. Addressing this crisis requires urgent, coordinated global efforts to reduce emissions, adopt renewable energy, and promote sustainable practices to safeguard the planet for future generations.\", type='TextMessage'), StopMessage(source='DiGraphStopAgent', models_usage=None, metadata={}, content='Digraph execution is complete', type='StopMessage')] stop_reason='Stop message received'\n"
     ]
    }
   ],
   "source": [
    "# Use `asyncio.run(...)` and wrap the below in a async function when running in a script.\n",
    "stream = flow.run_stream(task=\"Write a short paragraph about climate change.\")\n",
    "async for event in stream:  # type: ignore\n",
    "    print(event)\n",
    "# Use Console(flow.run_stream(...)) for better formatting in console."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5157cfbf",
   "metadata": {},
   "source": [
    "### Parallel Flow with Join\n",
    "\n",
    "We now create a slightly more complex flow:\n",
    "\n",
    "- A **writer** drafts a paragraph.\n",
    "- Two **editors** independently edit for grammar and style (parallel fan-out).\n",
    "- A **final reviewer** consolidates their edits (join).\n",
    "\n",
    "Execution starts at the **writer**, fans out to **editor1** and **editor2** simultaneously, and then both feed into the **final reviewer**.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a54d2454",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "---------- TextMessage (user) ----------\n",
      "Write a short paragraph about climate change.\n",
      "---------- TextMessage (writer) ----------\n",
      "Climate change refers to long-term shifts in weather patterns and global temperatures, largely driven by human activities such as burning fossil fuels, deforestation, and industrial processes. These activities increase concentrations of greenhouse gases like carbon dioxide and methane in the atmosphere, leading to global warming. The impacts of climate change include more frequent and severe weather events, rising sea levels, melting glaciers, and disruptions to ecosystems and agriculture. Addressing this urgent issue requires international cooperation, significant shifts toward renewable energy sources, and sustainable practices to reduce our carbon footprint and protect the planet for future generations.\n",
      "---------- TextMessage (editor1) ----------\n",
      "Climate change refers to long-term shifts in weather patterns and global temperatures, largely driven by human activities such as burning fossil fuels, deforestation, and industrial processes. These activities increase concentrations of greenhouse gases like carbon dioxide and methane in the atmosphere, leading to global warming. The impacts of climate change include more frequent and severe weather events, rising sea levels, melting glaciers, and disruptions to ecosystems and agriculture. Addressing this urgent issue requires international cooperation, significant shifts toward renewable energy sources, and sustainable practices to reduce our carbon footprint and protect the planet for future generations.\n",
      "---------- TextMessage (editor2) ----------\n",
      "Climate change involves long-term alterations in weather patterns and global temperatures, primarily caused by human activities like burning fossil fuels, deforestation, and industrial processes. These actions elevate levels of greenhouse gases such as carbon dioxide and methane, resulting in global warming. Its consequences are widespread, including more frequent and intense storms, rising sea levels, melting glaciers, and disturbances to ecosystems and agriculture. Combating this crisis demands international collaboration, a swift transition to renewable energy, and sustainable practices to cut carbon emissions, ensuring a healthier planet for future generations.\n",
      "---------- TextMessage (final_reviewer) ----------\n",
      "Climate change involves long-term alterations in weather patterns and global temperatures, primarily caused by human activities such as burning fossil fuels, deforestation, and industrial processes. These actions increase levels of greenhouse gases like carbon dioxide and methane, leading to global warming. Its consequences include more frequent and intense storms, rising sea levels, melting glaciers, and disruptions to ecosystems and agriculture. Addressing this crisis requires international collaboration, a swift transition to renewable energy, and sustainable practices to reduce carbon emissions, ensuring a healthier planet for future generations.\n",
      "---------- StopMessage (DiGraphStopAgent) ----------\n",
      "Digraph execution is complete\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "TaskResult(messages=[TextMessage(source='user', models_usage=None, metadata={}, content='Write a short paragraph about climate change.', type='TextMessage'), TextMessage(source='writer', models_usage=RequestUsage(prompt_tokens=28, completion_tokens=113), metadata={}, content='Climate change refers to long-term shifts in weather patterns and global temperatures, largely driven by human activities such as burning fossil fuels, deforestation, and industrial processes. These activities increase concentrations of greenhouse gases like carbon dioxide and methane in the atmosphere, leading to global warming. The impacts of climate change include more frequent and severe weather events, rising sea levels, melting glaciers, and disruptions to ecosystems and agriculture. Addressing this urgent issue requires international cooperation, significant shifts toward renewable energy sources, and sustainable practices to reduce our carbon footprint and protect the planet for future generations.', type='TextMessage'), TextMessage(source='editor1', models_usage=RequestUsage(prompt_tokens=144, completion_tokens=113), metadata={}, content='Climate change refers to long-term shifts in weather patterns and global temperatures, largely driven by human activities such as burning fossil fuels, deforestation, and industrial processes. These activities increase concentrations of greenhouse gases like carbon dioxide and methane in the atmosphere, leading to global warming. The impacts of climate change include more frequent and severe weather events, rising sea levels, melting glaciers, and disruptions to ecosystems and agriculture. Addressing this urgent issue requires international cooperation, significant shifts toward renewable energy sources, and sustainable practices to reduce our carbon footprint and protect the planet for future generations.', type='TextMessage'), TextMessage(source='editor2', models_usage=RequestUsage(prompt_tokens=263, completion_tokens=107), metadata={}, content='Climate change involves long-term alterations in weather patterns and global temperatures, primarily caused by human activities like burning fossil fuels, deforestation, and industrial processes. These actions elevate levels of greenhouse gases such as carbon dioxide and methane, resulting in global warming. Its consequences are widespread, including more frequent and intense storms, rising sea levels, melting glaciers, and disturbances to ecosystems and agriculture. Combating this crisis demands international collaboration, a swift transition to renewable energy, and sustainable practices to cut carbon emissions, ensuring a healthier planet for future generations.', type='TextMessage'), TextMessage(source='final_reviewer', models_usage=RequestUsage(prompt_tokens=383, completion_tokens=104), metadata={}, content='Climate change involves long-term alterations in weather patterns and global temperatures, primarily caused by human activities such as burning fossil fuels, deforestation, and industrial processes. These actions increase levels of greenhouse gases like carbon dioxide and methane, leading to global warming. Its consequences include more frequent and intense storms, rising sea levels, melting glaciers, and disruptions to ecosystems and agriculture. Addressing this crisis requires international collaboration, a swift transition to renewable energy, and sustainable practices to reduce carbon emissions, ensuring a healthier planet for future generations.', type='TextMessage'), StopMessage(source='DiGraphStopAgent', models_usage=None, metadata={}, content='Digraph execution is complete', type='StopMessage')], stop_reason='Stop message received')"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from autogen_agentchat.agents import AssistantAgent\n",
    "from autogen_agentchat.teams import DiGraphBuilder, GraphFlow\n",
    "from autogen_agentchat.ui import Console\n",
    "from autogen_ext.models.openai import OpenAIChatCompletionClient\n",
    "\n",
    "# Create an OpenAI model client\n",
    "client = OpenAIChatCompletionClient(model=\"gpt-4.1-nano\")\n",
    "\n",
    "# Create the writer agent\n",
    "writer = AssistantAgent(\"writer\", model_client=client, system_message=\"Draft a short paragraph on climate change.\")\n",
    "\n",
    "# Create two editor agents\n",
    "editor1 = AssistantAgent(\"editor1\", model_client=client, system_message=\"Edit the paragraph for grammar.\")\n",
    "\n",
    "editor2 = AssistantAgent(\"editor2\", model_client=client, system_message=\"Edit the paragraph for style.\")\n",
    "\n",
    "# Create the final reviewer agent\n",
    "final_reviewer = AssistantAgent(\n",
    "    \"final_reviewer\",\n",
    "    model_client=client,\n",
    "    system_message=\"Consolidate the grammar and style edits into a final version.\",\n",
    ")\n",
    "\n",
    "# Build the workflow graph\n",
    "builder = DiGraphBuilder()\n",
    "builder.add_node(writer).add_node(editor1).add_node(editor2).add_node(final_reviewer)\n",
    "\n",
    "# Fan-out from writer to editor1 and editor2\n",
    "builder.add_edge(writer, editor1)\n",
    "builder.add_edge(writer, editor2)\n",
    "\n",
    "# Fan-in both editors into final reviewer\n",
    "builder.add_edge(editor1, final_reviewer)\n",
    "builder.add_edge(editor2, final_reviewer)\n",
    "\n",
    "# Build and validate the graph\n",
    "graph = builder.build()\n",
    "\n",
    "# Create the flow\n",
    "flow = GraphFlow(\n",
    "    participants=builder.get_participants(),\n",
    "    graph=graph,\n",
    ")\n",
    "\n",
    "# Run the workflow\n",
    "await Console(flow.run_stream(task=\"Write a short paragraph about climate change.\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0343182c",
   "metadata": {},
   "source": [
    "## Message Filtering\n",
    "\n",
    "### Execution Graph vs. Message Graph\n",
    "\n",
    "In {py:class}`~autogen_agentchat.teams.GraphFlow`, the **execution graph** is defined using \n",
    "{py:class}`~autogen_agentchat.teams.DiGraph`, which controls the order in which agents execute.\n",
    "However, the execution graph does not control what messages an agent receives from other agents.\n",
    "By default, all messages are sent to all agents in the graph.\n",
    "\n",
    "**Message filtering** is a separate feature that allows you to filter the messages\n",
    "received by each agent and limiting their model context to only the relevant information.\n",
    "The set of message filters defines the **message graph** in the flow.\n",
    "\n",
    "Specifying the message graph can help with:\n",
    "- Reduce hallucinations\n",
    "- Control memory load\n",
    "- Focus agents only on relevant information\n",
    "\n",
    "You can use {py:class}`~autogen_agentchat.agents.MessageFilterAgent` together with {py:class}`~autogen_agentchat.agents.MessageFilterConfig` and {py:class}`~autogen_agentchat.agents.PerSourceFilter` to define these rules."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2a59af03",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "---------- TextMessage (user) ----------\n",
      "Summarize key facts about climate change.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "---------- TextMessage (researcher) ----------\n",
      "Certainly! Here are some key facts about climate change:\n",
      "\n",
      "1. **Global Warming**: Earth's average surface temperature has increased significantly over the past century, primarily due to human activities.\n",
      "2. **Greenhouse Gas Emissions**: The main contributors are carbon dioxide (CO₂), methane (CH₄), and nitrous oxide (N₂O), resulting from burning fossil fuels, deforestation, and industrial processes.\n",
      "3. **Impacts on Weather and Climate**: Climate change leads to more frequent and severe heatwaves, storms, droughts, and heavy rainfall.\n",
      "4. **Rising Sea Levels**: Melting polar ice caps and glaciers, along with thermal expansion of seawater, are causing sea levels to rise.\n",
      "5. **Effects on Ecosystems**: Altered habitats threaten plant and animal species, leading to biodiversity loss.\n",
      "6. **Human Health and Societies**: Climate change contributes to health issues, food and water insecurity, and displacement of populations.\n",
      "7. **Global Response**: International efforts like the Paris Agreement aim to limit temperature rise, promote renewable energy, and reduce emissions.\n",
      "8. **Urgency**: Addressing climate change requires immediate, concerted actions to mitigate further damage and adapt to changes.\n",
      "\n",
      "Let me know if you want more detailed information on any of these points!\n",
      "---------- TextMessage (analyst) ----------\n",
      "Your summary effectively covers the fundamental aspects of climate change and presents them clearly. Here are some suggestions to improve clarity, depth, and engagement:\n",
      "\n",
      "1. Enhance structure with subheadings: Organize points into thematic sections (e.g., Causes, Effects, Responses) for easier navigation.\n",
      "2. Add recent context or data: Incorporate the latest statistics or notable recent events to emphasize urgency.\n",
      "3. Emphasize solutions: Briefly mention specific mitigation and adaptation strategies beyond international agreements.\n",
      "4. Use more precise language: For example, specify the amount of temperature increase globally (~1.2°C since pre-industrial times).\n",
      "5. Incorporate the importance of individual actions: Highlight how personal choices contribute to climate efforts.\n",
      "6. Mention climate feedback loops: Briefly note how certain effects (like melting ice) can accelerate warming.\n",
      "\n",
      "**Improved Version:**\n",
      "\n",
      "---\n",
      "\n",
      "**Overview of Climate Change**\n",
      "\n",
      "**Causes:**\n",
      "- Human activities, especially burning fossil fuels, deforestation, and industrial processes, have led to increased concentrations of greenhouse gases such as carbon dioxide (CO₂), methane (CH₄), and nitrous oxide (N₂O).\n",
      "- Since the late 19th century, Earth's average surface temperature has risen by approximately 1.2°C, with the past decade being the warmest on record.\n",
      "\n",
      "**Impacts:**\n",
      "- The changing climate causes more frequent and intense heatwaves, storms, droughts, and heavy rainfall events.\n",
      "- Melting polar ice caps and glaciers, along with thermal expansion, are raising sea levels, threatening coastal communities.\n",
      "- Ecosystems are shifting, leading to habitat loss and risking biodiversity, with some species facing extinction.\n",
      "- Human health and societies are affected through increased heat-related illnesses, food and water insecurity, and displacement due to extreme weather events.\n",
      "\n",
      "**Global Response and Solutions:**\n",
      "- International agreements like the Paris Agreement aim to limit global temperature rise well below 2°C.\n",
      "- Strategies include transitioning to renewable energy sources, increasing energy efficiency, reforestation, and sustainable land use.\n",
      "- Community and individual actions—reducing carbon footprints, supporting sustainable policies, and raising awareness—are essential components.\n",
      "\n",
      "**Urgency and Call to Action:**\n",
      "- Immediate, coordinated efforts are critical to mitigate irreversible damage and adapt to ongoing changes.\n",
      "- Every sector, from government to individual, has a role to play in creating a sustainable future.\n",
      "\n",
      "---\n",
      "\n",
      "Let me know if you'd like a more detailed explanation of any section or additional statistical data!\n",
      "---------- TextMessage (presenter) ----------\n",
      "**Slide Title:**  \n",
      "**Climate Change: Causes, Impacts & Solutions**\n",
      "\n",
      "**Causes:**  \n",
      "- Emissions from burning fossil fuels, deforestation, industrial activities  \n",
      "- Greenhouse gases (CO₂, CH₄, N₂O) have increased significantly  \n",
      "- Global temperature has risen by ~1.2°C since pre-industrial times  \n",
      "\n",
      "**Impacts:**  \n",
      "- More frequent heatwaves, storms, droughts, and heavy rainfall  \n",
      "- Melting ice caps and rising sea levels threaten coastal areas  \n",
      "- Habitat loss and decreased biodiversity  \n",
      "- Health risks and societal disruptions  \n",
      "\n",
      "**Responses & Solutions:**  \n",
      "- International efforts like the Paris Agreement aim to limit warming  \n",
      "- Transitioning to renewable energy, energy efficiency, reforestation  \n",
      "- Community and individual actions: reducing carbon footprints and raising awareness  \n",
      "\n",
      "**Urgency:**  \n",
      "- Immediate, coordinated action is essential to prevent irreversible damage  \n",
      "- Everyone has a role in building a sustainable future\n",
      "---------- StopMessage (DiGraphStopAgent) ----------\n",
      "Digraph execution is complete\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "TaskResult(messages=[TextMessage(source='user', models_usage=None, metadata={}, content='Summarize key facts about climate change.', type='TextMessage'), TextMessage(source='researcher', models_usage=RequestUsage(prompt_tokens=30, completion_tokens=267), metadata={}, content=\"Certainly! Here are some key facts about climate change:\\n\\n1. **Global Warming**: Earth's average surface temperature has increased significantly over the past century, primarily due to human activities.\\n2. **Greenhouse Gas Emissions**: The main contributors are carbon dioxide (CO₂), methane (CH₄), and nitrous oxide (N₂O), resulting from burning fossil fuels, deforestation, and industrial processes.\\n3. **Impacts on Weather and Climate**: Climate change leads to more frequent and severe heatwaves, storms, droughts, and heavy rainfall.\\n4. **Rising Sea Levels**: Melting polar ice caps and glaciers, along with thermal expansion of seawater, are causing sea levels to rise.\\n5. **Effects on Ecosystems**: Altered habitats threaten plant and animal species, leading to biodiversity loss.\\n6. **Human Health and Societies**: Climate change contributes to health issues, food and water insecurity, and displacement of populations.\\n7. **Global Response**: International efforts like the Paris Agreement aim to limit temperature rise, promote renewable energy, and reduce emissions.\\n8. **Urgency**: Addressing climate change requires immediate, concerted actions to mitigate further damage and adapt to changes.\\n\\nLet me know if you want more detailed information on any of these points!\", type='TextMessage'), TextMessage(source='analyst', models_usage=RequestUsage(prompt_tokens=287, completion_tokens=498), metadata={}, content=\"Your summary effectively covers the fundamental aspects of climate change and presents them clearly. Here are some suggestions to improve clarity, depth, and engagement:\\n\\n1. Enhance structure with subheadings: Organize points into thematic sections (e.g., Causes, Effects, Responses) for easier navigation.\\n2. Add recent context or data: Incorporate the latest statistics or notable recent events to emphasize urgency.\\n3. Emphasize solutions: Briefly mention specific mitigation and adaptation strategies beyond international agreements.\\n4. Use more precise language: For example, specify the amount of temperature increase globally (~1.2°C since pre-industrial times).\\n5. Incorporate the importance of individual actions: Highlight how personal choices contribute to climate efforts.\\n6. Mention climate feedback loops: Briefly note how certain effects (like melting ice) can accelerate warming.\\n\\n**Improved Version:**\\n\\n---\\n\\n**Overview of Climate Change**\\n\\n**Causes:**\\n- Human activities, especially burning fossil fuels, deforestation, and industrial processes, have led to increased concentrations of greenhouse gases such as carbon dioxide (CO₂), methane (CH₄), and nitrous oxide (N₂O).\\n- Since the late 19th century, Earth's average surface temperature has risen by approximately 1.2°C, with the past decade being the warmest on record.\\n\\n**Impacts:**\\n- The changing climate causes more frequent and intense heatwaves, storms, droughts, and heavy rainfall events.\\n- Melting polar ice caps and glaciers, along with thermal expansion, are raising sea levels, threatening coastal communities.\\n- Ecosystems are shifting, leading to habitat loss and risking biodiversity, with some species facing extinction.\\n- Human health and societies are affected through increased heat-related illnesses, food and water insecurity, and displacement due to extreme weather events.\\n\\n**Global Response and Solutions:**\\n- International agreements like the Paris Agreement aim to limit global temperature rise well below 2°C.\\n- Strategies include transitioning to renewable energy sources, increasing energy efficiency, reforestation, and sustainable land use.\\n- Community and individual actions—reducing carbon footprints, supporting sustainable policies, and raising awareness—are essential components.\\n\\n**Urgency and Call to Action:**\\n- Immediate, coordinated efforts are critical to mitigate irreversible damage and adapt to ongoing changes.\\n- Every sector, from government to individual, has a role to play in creating a sustainable future.\\n\\n---\\n\\nLet me know if you'd like a more detailed explanation of any section or additional statistical data!\", type='TextMessage'), TextMessage(source='presenter', models_usage=RequestUsage(prompt_tokens=521, completion_tokens=192), metadata={}, content='**Slide Title:**  \\n**Climate Change: Causes, Impacts & Solutions**\\n\\n**Causes:**  \\n- Emissions from burning fossil fuels, deforestation, industrial activities  \\n- Greenhouse gases (CO₂, CH₄, N₂O) have increased significantly  \\n- Global temperature has risen by ~1.2°C since pre-industrial times  \\n\\n**Impacts:**  \\n- More frequent heatwaves, storms, droughts, and heavy rainfall  \\n- Melting ice caps and rising sea levels threaten coastal areas  \\n- Habitat loss and decreased biodiversity  \\n- Health risks and societal disruptions  \\n\\n**Responses & Solutions:**  \\n- International efforts like the Paris Agreement aim to limit warming  \\n- Transitioning to renewable energy, energy efficiency, reforestation  \\n- Community and individual actions: reducing carbon footprints and raising awareness  \\n\\n**Urgency:**  \\n- Immediate, coordinated action is essential to prevent irreversible damage  \\n- Everyone has a role in building a sustainable future', type='TextMessage'), StopMessage(source='DiGraphStopAgent', models_usage=None, metadata={}, content='Digraph execution is complete', type='StopMessage')], stop_reason='Stop message received')"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from autogen_agentchat.agents import AssistantAgent, MessageFilterAgent, MessageFilterConfig, PerSourceFilter\n",
    "from autogen_agentchat.teams import DiGraphBuilder, GraphFlow\n",
    "from autogen_agentchat.ui import Console\n",
    "from autogen_ext.models.openai import OpenAIChatCompletionClient\n",
    "\n",
    "# Model client\n",
    "client = OpenAIChatCompletionClient(model=\"gpt-4.1-nano\")\n",
    "\n",
    "# Create agents\n",
    "researcher = AssistantAgent(\n",
    "    \"researcher\", model_client=client, system_message=\"Summarize key facts about climate change.\"\n",
    ")\n",
    "analyst = AssistantAgent(\"analyst\", model_client=client, system_message=\"Review the summary and suggest improvements.\")\n",
    "presenter = AssistantAgent(\n",
    "    \"presenter\", model_client=client, system_message=\"Prepare a presentation slide based on the final summary.\"\n",
    ")\n",
    "\n",
    "# Apply message filtering\n",
    "filtered_analyst = MessageFilterAgent(\n",
    "    name=\"analyst\",\n",
    "    wrapped_agent=analyst,\n",
    "    filter=MessageFilterConfig(per_source=[PerSourceFilter(source=\"researcher\", position=\"last\", count=1)]),\n",
    ")\n",
    "\n",
    "filtered_presenter = MessageFilterAgent(\n",
    "    name=\"presenter\",\n",
    "    wrapped_agent=presenter,\n",
    "    filter=MessageFilterConfig(per_source=[PerSourceFilter(source=\"analyst\", position=\"last\", count=1)]),\n",
    ")\n",
    "\n",
    "# Build the flow\n",
    "builder = DiGraphBuilder()\n",
    "builder.add_node(researcher).add_node(filtered_analyst).add_node(filtered_presenter)\n",
    "builder.add_edge(researcher, filtered_analyst).add_edge(filtered_analyst, filtered_presenter)\n",
    "\n",
    "# Create the flow\n",
    "flow = GraphFlow(\n",
    "    participants=builder.get_participants(),\n",
    "    graph=builder.build(),\n",
    ")\n",
    "\n",
    "# Run the flow\n",
    "await Console(flow.run_stream(task=\"Summarize key facts about climate change.\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f7309529",
   "metadata": {},
   "source": [
    "## 🔁 Advanced Example: Conditional Loop + Filtered Summary\n",
    "\n",
    "This example demonstrates:\n",
    "\n",
    "- A loop between generator and reviewer (which exits when reviewer says \"APPROVE\")\n",
    "- A summarizer agent that only sees the first user input and the last reviewer message\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "af297db2",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "---------- TextMessage (user) ----------\n",
      "Brainstorm ways to reduce plastic waste.\n",
      "---------- TextMessage (generator) ----------\n",
      "Here are some creative ideas to help reduce plastic waste:\n",
      "\n",
      "1. **Refill Stations**: Create refill stations for common household liquids (like soaps, shampoos, and detergents) where people can bring their own containers to fill up.\n",
      "\n",
      "2. **DIY Kits**: Offer DIY kits for making eco-friendly products, such as beeswax wraps, reusable bags, or natural cleaning solutions.\n",
      "\n",
      "3. **Community Swap Events**: Organize swap events where people can bring unwanted items, including clothing and household products, to exchange instead of purchasing new items.\n",
      "\n",
      "4. **Plastic-Free Challenge**: Launch a community-wide challenge encouraging residents to go plastic-free for a month, sharing tips and experiences on social media.\n",
      "\n",
      "5. **Incentivize Businesses**: Create incentives for local businesses that implement sustainable practices, like providing discounts to customers who bring their own containers or bags.\n",
      "\n",
      "6. **Educational Campaigns**: Partner with schools to educate children about the impact of plastic waste and encourage them to take home messages to their families.\n",
      "\n",
      "7. **Plastic-Free Shopping Zones**: Designate certain areas in town as plastic-free zones where businesses agree to eliminate single-use plastics.\n",
      "\n",
      "8. **Upcycling Workshops**: Host workshops teaching people how to upcycle plastic waste into art, furniture, or home decor.\n",
      "\n",
      "9. **Composting Competition**: Encourage households to compost food waste and offer a competition for the best composting garden to foster eco-awareness.\n",
      "\n",
      "10. **Zero-Waste Stores**: Support or start zero-waste stores that sell bulk goods, allowing customers to shop with their own containers.\n",
      "\n",
      "11. **Mobile Recycling Units**: Implement mobile recycling units that visit neighborhoods to educate residents on recycling properly and collect recyclables.\n",
      "\n",
      "12. **Plastic Offset Programs**: Create programs that allow individuals and companies to offset their plastic usage through donations to initiatives that remove plastic from oceans.\n",
      "\n",
      "13. **Collaboration with Influencers**: Partner with social media influencers to spread the message about reducing plastic waste and promote sustainable alternatives.\n",
      "\n",
      "14. **Sustainable Product Market**: Organize a market dedicated exclusively to sustainable products and services, showcasing local vendors who prioritize eco-friendly practices.\n",
      "\n",
      "15. **Plastic Waste Art Installations**: Collaborate with artists to create public installations made from recycled plastic, raising awareness of the plastic problem in a visually impactful way.\n",
      "\n",
      "16. **Interactive Apps**: Develop apps that track plastic usage and provide personalized tips for reducing plastic consumption based on user habits.\n",
      "\n",
      "17. **Corporate Partnerships**: Work with businesses to develop corporate responsibility programs focused on reducing plastic use in their operations and packaging.\n",
      "\n",
      "18. **Legislation Advocacy**: Promote local policies that restrict single-use plastics or support more effective recycling programs.\n",
      "\n",
      "19. **Public Transportation Awareness**: Encourage public transportation usage by providing eco-friendly incentives for those who walk, bike, or use buses instead of cars.\n",
      "\n",
      "20. **Create a Local Plastic Waste Repository**: Start a community hub where individuals and artists can drop off plastic waste for reuse in projects or art pieces.\n",
      "\n",
      "By implementing these ideas, communities can take significant steps toward reducing plastic waste and fostering a sustainable future.\n",
      "---------- TextMessage (reviewer) ----------\n",
      "These ideas present a comprehensive and practical approach to reducing plastic waste within communities. Here’s some feedback and considerations for each suggestion:\n",
      "\n",
      "1. **Refill Stations**: Great idea; consider partnering with local health and wellness shops for broader adoption.\n",
      "   \n",
      "2. **DIY Kits**: Ensure kits include clear instructions and safety guidance to promote user-friendliness.\n",
      "\n",
      "3. **Community Swap Events**: Promote these as regular events to build a sense of community and reinforce sustainable habits.\n",
      "\n",
      "4. **Plastic-Free Challenge**: Consider creating a dedicated hashtag to track participants’ journeys and foster engagement online.\n",
      "\n",
      "5. **Incentivize Businesses**: Work on a simple certification system for sustainable businesses to encourage participation and recognition.\n",
      "\n",
      "6. **Educational Campaigns**: Tailor content to different age groups to maximize impact across the community.\n",
      "\n",
      "7. **Plastic-Free Shopping Zones**: Consider involving local government for support and promotion, which can increase visibility and compliance.\n",
      "\n",
      "8. **Upcycling Workshops**: Source materials locally for workshops to decrease transportation emissions and support local businesses.\n",
      "\n",
      "9. **Composting Competition**: Collaborate with gardening clubs for expert insights and to broaden participation in community gardening.\n",
      "\n",
      "10. **Zero-Waste Stores**: Explore online sales options to enhance accessibility while retaining the focus on zero-waste practices.\n",
      "\n",
      "11. **Mobile Recycling Units**: Train volunteers for effective community engagement and education during visits.\n",
      "\n",
      "12. **Plastic Offset Programs**: Emphasize transparency in how donations are used to build trust within the community.\n",
      "\n",
      "13. **Collaboration with Influencers**: Ensure influencers have a genuine commitment to sustainability to ensure credible messaging.\n",
      "\n",
      "14. **Sustainable Product Market**: Regularly invite new vendors to keep the market fresh and encourage innovation in sustainable products.\n",
      "\n",
      "15. **Plastic Waste Art Installations**: Consider educational plaques accompanying installations that inform viewers about the issues of plastic waste.\n",
      "\n",
      "16. **Interactive Apps**: Include gamification elements to encourage increased user engagement and sharing among friends.\n",
      "\n",
      "17. **Corporate Partnerships**: Develop case studies or success stories to showcase the benefits of reduced plastic use for businesses.\n",
      "\n",
      "18. **Legislation Advocacy**: Mobilize community members to become advocates themselves, creating a grass-roots effort for policy change.\n",
      "\n",
      "19. **Public Transportation Awareness**: Explore partnerships with public transit systems for eco-friendly promotions.\n",
      "\n",
      "20. **Create a Local Plastic Waste Repository**: Establish partnerships with local craft schools or organizations to enhance creativity and use of the repository.\n",
      "\n",
      "Overall, these ideas have high potential for impactful implementation. Emphasizing community engagement, education, and ongoing support will help ensure their success. **APPROVE**.\n",
      "---------- TextMessage (summary) ----------\n",
      "The user requested brainstorming ideas to reduce plastic waste, looking for practical and impactful solutions. The reviewer provided detailed feedback on each suggested idea, indicating strengths and considerations for improvement, such as involving local businesses, enhancing community engagement, and promoting educational initiatives. The final feedback indicates that the suggestions have great potential and emphasizes the importance of community involvement and education for successful implementation, culminating in an overall approval of the ideas presented.\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "TaskResult(messages=[TextMessage(id='eca90b4f-a8cc-4f06-9b42-d8387caf338e', source='user', models_usage=None, metadata={}, created_at=datetime.datetime(2025, 7, 15, 1, 48, 51, 648989, tzinfo=datetime.timezone.utc), content='Brainstorm ways to reduce plastic waste.', type='TextMessage'), TextMessage(id='29767cbd-ae8d-4dfb-be57-7f982aaddc4b', source='generator', models_usage=RequestUsage(prompt_tokens=27, completion_tokens=627), metadata={}, created_at=datetime.datetime(2025, 7, 15, 1, 49, 6, 788238, tzinfo=datetime.timezone.utc), content='Here are some creative ideas to help reduce plastic waste:\\n\\n1. **Refill Stations**: Create refill stations for common household liquids (like soaps, shampoos, and detergents) where people can bring their own containers to fill up.\\n\\n2. **DIY Kits**: Offer DIY kits for making eco-friendly products, such as beeswax wraps, reusable bags, or natural cleaning solutions.\\n\\n3. **Community Swap Events**: Organize swap events where people can bring unwanted items, including clothing and household products, to exchange instead of purchasing new items.\\n\\n4. **Plastic-Free Challenge**: Launch a community-wide challenge encouraging residents to go plastic-free for a month, sharing tips and experiences on social media.\\n\\n5. **Incentivize Businesses**: Create incentives for local businesses that implement sustainable practices, like providing discounts to customers who bring their own containers or bags.\\n\\n6. **Educational Campaigns**: Partner with schools to educate children about the impact of plastic waste and encourage them to take home messages to their families.\\n\\n7. **Plastic-Free Shopping Zones**: Designate certain areas in town as plastic-free zones where businesses agree to eliminate single-use plastics.\\n\\n8. **Upcycling Workshops**: Host workshops teaching people how to upcycle plastic waste into art, furniture, or home decor.\\n\\n9. **Composting Competition**: Encourage households to compost food waste and offer a competition for the best composting garden to foster eco-awareness.\\n\\n10. **Zero-Waste Stores**: Support or start zero-waste stores that sell bulk goods, allowing customers to shop with their own containers.\\n\\n11. **Mobile Recycling Units**: Implement mobile recycling units that visit neighborhoods to educate residents on recycling properly and collect recyclables.\\n\\n12. **Plastic Offset Programs**: Create programs that allow individuals and companies to offset their plastic usage through donations to initiatives that remove plastic from oceans.\\n\\n13. **Collaboration with Influencers**: Partner with social media influencers to spread the message about reducing plastic waste and promote sustainable alternatives.\\n\\n14. **Sustainable Product Market**: Organize a market dedicated exclusively to sustainable products and services, showcasing local vendors who prioritize eco-friendly practices.\\n\\n15. **Plastic Waste Art Installations**: Collaborate with artists to create public installations made from recycled plastic, raising awareness of the plastic problem in a visually impactful way.\\n\\n16. **Interactive Apps**: Develop apps that track plastic usage and provide personalized tips for reducing plastic consumption based on user habits.\\n\\n17. **Corporate Partnerships**: Work with businesses to develop corporate responsibility programs focused on reducing plastic use in their operations and packaging.\\n\\n18. **Legislation Advocacy**: Promote local policies that restrict single-use plastics or support more effective recycling programs.\\n\\n19. **Public Transportation Awareness**: Encourage public transportation usage by providing eco-friendly incentives for those who walk, bike, or use buses instead of cars.\\n\\n20. **Create a Local Plastic Waste Repository**: Start a community hub where individuals and artists can drop off plastic waste for reuse in projects or art pieces.\\n\\nBy implementing these ideas, communities can take significant steps toward reducing plastic waste and fostering a sustainable future.', type='TextMessage'), TextMessage(id='54e02028-0239-4809-8163-af60745e6b9d', source='reviewer', models_usage=RequestUsage(prompt_tokens=671, completion_tokens=532), metadata={}, created_at=datetime.datetime(2025, 7, 15, 1, 49, 17, 327641, tzinfo=datetime.timezone.utc), content='These ideas present a comprehensive and practical approach to reducing plastic waste within communities. Here’s some feedback and considerations for each suggestion:\\n\\n1. **Refill Stations**: Great idea; consider partnering with local health and wellness shops for broader adoption.\\n   \\n2. **DIY Kits**: Ensure kits include clear instructions and safety guidance to promote user-friendliness.\\n\\n3. **Community Swap Events**: Promote these as regular events to build a sense of community and reinforce sustainable habits.\\n\\n4. **Plastic-Free Challenge**: Consider creating a dedicated hashtag to track participants’ journeys and foster engagement online.\\n\\n5. **Incentivize Businesses**: Work on a simple certification system for sustainable businesses to encourage participation and recognition.\\n\\n6. **Educational Campaigns**: Tailor content to different age groups to maximize impact across the community.\\n\\n7. **Plastic-Free Shopping Zones**: Consider involving local government for support and promotion, which can increase visibility and compliance.\\n\\n8. **Upcycling Workshops**: Source materials locally for workshops to decrease transportation emissions and support local businesses.\\n\\n9. **Composting Competition**: Collaborate with gardening clubs for expert insights and to broaden participation in community gardening.\\n\\n10. **Zero-Waste Stores**: Explore online sales options to enhance accessibility while retaining the focus on zero-waste practices.\\n\\n11. **Mobile Recycling Units**: Train volunteers for effective community engagement and education during visits.\\n\\n12. **Plastic Offset Programs**: Emphasize transparency in how donations are used to build trust within the community.\\n\\n13. **Collaboration with Influencers**: Ensure influencers have a genuine commitment to sustainability to ensure credible messaging.\\n\\n14. **Sustainable Product Market**: Regularly invite new vendors to keep the market fresh and encourage innovation in sustainable products.\\n\\n15. **Plastic Waste Art Installations**: Consider educational plaques accompanying installations that inform viewers about the issues of plastic waste.\\n\\n16. **Interactive Apps**: Include gamification elements to encourage increased user engagement and sharing among friends.\\n\\n17. **Corporate Partnerships**: Develop case studies or success stories to showcase the benefits of reduced plastic use for businesses.\\n\\n18. **Legislation Advocacy**: Mobilize community members to become advocates themselves, creating a grass-roots effort for policy change.\\n\\n19. **Public Transportation Awareness**: Explore partnerships with public transit systems for eco-friendly promotions.\\n\\n20. **Create a Local Plastic Waste Repository**: Establish partnerships with local craft schools or organizations to enhance creativity and use of the repository.\\n\\nOverall, these ideas have high potential for impactful implementation. Emphasizing community engagement, education, and ongoing support will help ensure their success. **APPROVE**.', type='TextMessage'), TextMessage(id='55409dc3-9766-4071-ab85-0b3125cb59c7', source='summary', models_usage=RequestUsage(prompt_tokens=570, completion_tokens=82), metadata={}, created_at=datetime.datetime(2025, 7, 15, 1, 49, 19, 442276, tzinfo=datetime.timezone.utc), content='The user requested brainstorming ideas to reduce plastic waste, looking for practical and impactful solutions. The reviewer provided detailed feedback on each suggested idea, indicating strengths and considerations for improvement, such as involving local businesses, enhancing community engagement, and promoting educational initiatives. The final feedback indicates that the suggestions have great potential and emphasizes the importance of community involvement and education for successful implementation, culminating in an overall approval of the ideas presented.', type='TextMessage')], stop_reason='Digraph execution is complete')"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from autogen_agentchat.agents import AssistantAgent, MessageFilterAgent, MessageFilterConfig, PerSourceFilter\n",
    "from autogen_agentchat.teams import (\n",
    "    DiGraphBuilder,\n",
    "    GraphFlow,\n",
    ")\n",
    "from autogen_agentchat.conditions import MaxMessageTermination\n",
    "from autogen_agentchat.ui import Console\n",
    "from autogen_ext.models.openai import OpenAIChatCompletionClient\n",
    "\n",
    "model_client = OpenAIChatCompletionClient(model=\"gpt-4o-mini\")\n",
    "\n",
    "# Agents\n",
    "generator = AssistantAgent(\"generator\", model_client=model_client, system_message=\"Generate a list of creative ideas.\")\n",
    "reviewer = AssistantAgent(\n",
    "    \"reviewer\",\n",
    "    model_client=model_client,\n",
    "    system_message=\"Review ideas and provide feedbacks, or just 'APPROVE' for final approval.\",\n",
    ")\n",
    "summarizer_core = AssistantAgent(\n",
    "    \"summary\", model_client=model_client, system_message=\"Summarize the user request and the final feedback.\"\n",
    ")\n",
    "\n",
    "# Filtered summarizer\n",
    "filtered_summarizer = MessageFilterAgent(\n",
    "    name=\"summary\",\n",
    "    wrapped_agent=summarizer_core,\n",
    "    filter=MessageFilterConfig(\n",
    "        per_source=[\n",
    "            PerSourceFilter(source=\"user\", position=\"first\", count=1),\n",
    "            PerSourceFilter(source=\"reviewer\", position=\"last\", count=1),\n",
    "        ]\n",
    "    ),\n",
    ")\n",
    "\n",
    "# Build graph with conditional loop\n",
    "builder = DiGraphBuilder()\n",
    "builder.add_node(generator).add_node(reviewer).add_node(filtered_summarizer)\n",
    "builder.add_edge(generator, reviewer)\n",
    "builder.add_edge(reviewer, filtered_summarizer, condition=lambda msg: \"APPROVE\" in msg.to_model_text())\n",
    "builder.add_edge(reviewer, generator, condition=lambda msg: \"APPROVE\" not in msg.to_model_text())\n",
    "builder.set_entry_point(generator)  # Set entry point to generator. Required if there are no source nodes.\n",
    "graph = builder.build()\n",
    "\n",
    "termination_condition = MaxMessageTermination(10)\n",
    "\n",
    "# Create the flow\n",
    "flow = GraphFlow(\n",
    "    participants=builder.get_participants(),\n",
    "    graph=graph,\n",
    "    termination_condition=termination_condition\n",
    ")\n",
    "\n",
    "# Run the flow and pretty print the output in the console\n",
    "await Console(flow.run_stream(task=\"Brainstorm ways to reduce plastic waste.\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4b39f9d6",
   "metadata": {},
   "source": [
    "## 🔁 Advanced Example: Cycles With Activation Group Examples\n",
    "\n",
    "The following examples demonstrate how to use `activation_group` and `activation_condition` to handle complex dependency patterns in cyclic graphs, especially when multiple paths lead to the same target node."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "791a4c47",
   "metadata": {},
   "source": [
    "### Example 1: Loop with Multiple Paths - \"All\" Activation (A→B→C→B)\n",
    "\n",
    "In this scenario, we have A → B → C → B, where B has two incoming edges (from A and from C). By default, B requires **all** its dependencies to be satisfied before executing.\n",
    "\n",
    "This example shows a review loop where both the initial input (A) and the feedback (C) must be processed before B can execute again."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "384f5831",
   "metadata": {},
   "outputs": [],
   "source": [
    "from autogen_agentchat.agents import AssistantAgent\n",
    "from autogen_agentchat.teams import DiGraphBuilder, GraphFlow\n",
    "from autogen_agentchat.conditions import MaxMessageTermination\n",
    "from autogen_agentchat.ui import Console\n",
    "from autogen_ext.models.openai import OpenAIChatCompletionClient\n",
    "\n",
    "# Model client\n",
    "client = OpenAIChatCompletionClient(model=\"gpt-4o-mini\")\n",
    "\n",
    "# Create agents for A→B→C→B→E scenario\n",
    "agent_a = AssistantAgent(\"A\", model_client=client, system_message=\"Start the process and provide initial input.\")\n",
    "agent_b = AssistantAgent(\n",
    "    \"B\",\n",
    "    model_client=client,\n",
    "    system_message=\"Process input from A or feedback from C. Say 'CONTINUE' if it's from A or 'STOP' if it's from C.\",\n",
    ")\n",
    "agent_c = AssistantAgent(\"C\", model_client=client, system_message=\"Review B's output and provide feedback.\")\n",
    "agent_e = AssistantAgent(\"E\", model_client=client, system_message=\"Finalize the process.\")\n",
    "\n",
    "# Build the graph with activation groups\n",
    "builder = DiGraphBuilder()\n",
    "builder.add_node(agent_a).add_node(agent_b).add_node(agent_c).add_node(agent_e)\n",
    "\n",
    "# A → B (initial path)\n",
    "builder.add_edge(agent_a, agent_b, activation_group=\"initial\")\n",
    "\n",
    "# B → C\n",
    "builder.add_edge(agent_b, agent_c, condition=\"CONTINUE\")\n",
    "\n",
    "# C → B (loop back - different activation group)\n",
    "builder.add_edge(agent_c, agent_b, activation_group=\"feedback\")\n",
    "\n",
    "# B → E (exit condition)\n",
    "builder.add_edge(agent_b, agent_e, condition=\"STOP\")\n",
    "\n",
    "termination_condition = MaxMessageTermination(10)\n",
    "# Build and create flow\n",
    "graph = builder.build()\n",
    "flow = GraphFlow(participants=[agent_a, agent_b, agent_c, agent_e], graph=graph, termination_condition=termination_condition)\n",
    "\n",
    "print(\"=== Example 1: A→B→C→B with 'All' Activation ===\")\n",
    "print(\"B will exit when it receives a message from C\")\n",
    "# await Console(flow.run_stream(task=\"Start a review process for a document.\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5dc08c64",
   "metadata": {},
   "source": [
    "### Example 2: Loop with Multiple Paths - \"Any\" Activation (A→B→(C1,C2)→B)\n",
    "\n",
    "In this more complex scenario, we have A → B → (C1, C2) → B, where:\n",
    "- B fans out to both C1 and C2 in parallel\n",
    "- Both C1 and C2 feed back to B \n",
    "- B uses \"any\" activation, meaning it executes as soon as **either** C1 or C2 completes\n",
    "\n",
    "This is useful for scenarios where you want the fastest response to trigger the next step.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "00f40293",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create agents for A→B→(C1,C2)→B scenario\n",
    "agent_a2 = AssistantAgent(\"A\", model_client=client, system_message=\"Initiate a task that needs parallel processing.\")\n",
    "agent_b2 = AssistantAgent(\n",
    "    \"B\",\n",
    "    model_client=client,\n",
    "    system_message=\"Coordinate parallel tasks. Say 'PROCESS' to start parallel work or 'DONE' to finish.\",\n",
    ")\n",
    "agent_c1 = AssistantAgent(\"C1\", model_client=client, system_message=\"Handle task type 1. Say 'C1_COMPLETE' when done.\")\n",
    "agent_c2 = AssistantAgent(\"C2\", model_client=client, system_message=\"Handle task type 2. Say 'C2_COMPLETE' when done.\")\n",
    "agent_e = AssistantAgent(\"E\", model_client=client, system_message=\"Finalize the process.\")\n",
    "\n",
    "# Build the graph with \"any\" activation\n",
    "builder2 = DiGraphBuilder()\n",
    "builder2.add_node(agent_a2).add_node(agent_b2).add_node(agent_c1).add_node(agent_c2).add_node(agent_e)\n",
    "\n",
    "# A → B (initial)\n",
    "builder2.add_edge(agent_a2, agent_b2)\n",
    "\n",
    "# B → C1 and B → C2 (parallel fan-out)\n",
    "builder2.add_edge(agent_b2, agent_c1, condition=\"PROCESS\")\n",
    "builder2.add_edge(agent_b2, agent_c2, condition=\"PROCESS\")\n",
    "\n",
    "# B → E (exit condition)\n",
    "builder2.add_edge(agent_b2, agent_e, condition=lambda msg: \"DONE\" in msg.to_model_text())\n",
    "\n",
    "# C1 → B and C2 → B (both in same activation group with \"any\" condition)\n",
    "builder2.add_edge(\n",
    "    agent_c1, agent_b2, activation_group=\"loop_back_group\", activation_condition=\"any\", condition=\"C1_COMPLETE\"\n",
    ")\n",
    "\n",
    "builder2.add_edge(\n",
    "    agent_c2, agent_b2, activation_group=\"loop_back_group\", activation_condition=\"any\", condition=\"C2_COMPLETE\"\n",
    ")\n",
    "\n",
    "# Build and create flow\n",
    "graph2 = builder2.build()\n",
    "flow2 = GraphFlow(participants=[agent_a2, agent_b2, agent_c1, agent_c2, agent_e], graph=graph2)\n",
    "\n",
    "print(\"=== Example 2: A→B→(C1,C2)→B with 'Any' Activation ===\")\n",
    "print(\"B will execute as soon as EITHER C1 OR C2 completes (whichever finishes first)\")\n",
    "# await Console(flow2.run_stream(task=\"Start a parallel processing task.\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7c56cd2e",
   "metadata": {},
   "source": [
    "### Example 3: Mixed Activation Groups\n",
    "\n",
    "This example shows how different activation groups can coexist in the same graph. We have a scenario where:\n",
    "- Node D receives inputs from multiple sources with different activation requirements\n",
    "- Some dependencies use \"all\" activation (must wait for all inputs)\n",
    "- Other dependencies use \"any\" activation (proceed on first input)\n",
    "\n",
    "This pattern is useful for complex workflows where different types of dependencies have different urgency levels.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "97f75ba1",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create agents for mixed activation scenario\n",
    "agent_a3 = AssistantAgent(\"A\", model_client=client, system_message=\"Provide critical input that must be processed.\")\n",
    "agent_b3 = AssistantAgent(\"B\", model_client=client, system_message=\"Provide secondary critical input.\")\n",
    "agent_c3 = AssistantAgent(\"C\", model_client=client, system_message=\"Provide optional quick input.\")\n",
    "agent_d3 = AssistantAgent(\"D\", model_client=client, system_message=\"Process inputs based on different priority levels.\")\n",
    "\n",
    "# Build graph with mixed activation groups\n",
    "builder3 = DiGraphBuilder()\n",
    "builder3.add_node(agent_a3).add_node(agent_b3).add_node(agent_c3).add_node(agent_d3)\n",
    "\n",
    "# Critical inputs that must ALL be present (activation_group=\"critical\", activation_condition=\"all\")\n",
    "builder3.add_edge(agent_a3, agent_d3, activation_group=\"critical\", activation_condition=\"all\")\n",
    "builder3.add_edge(agent_b3, agent_d3, activation_group=\"critical\", activation_condition=\"all\")\n",
    "\n",
    "# Optional input that can trigger execution on its own (activation_group=\"optional\", activation_condition=\"any\")\n",
    "builder3.add_edge(agent_c3, agent_d3, activation_group=\"optional\", activation_condition=\"any\")\n",
    "\n",
    "# Build and create flow\n",
    "graph3 = builder3.build()\n",
    "flow3 = GraphFlow(participants=[agent_a3, agent_b3, agent_c3, agent_d3], graph=graph3)\n",
    "\n",
    "print(\"=== Example 3: Mixed Activation Groups ===\")\n",
    "print(\"D will execute when:\")\n",
    "print(\"- BOTH A AND B complete (critical group with 'all' activation), OR\")\n",
    "print(\"- C completes (optional group with 'any' activation)\")\n",
    "print(\"This allows for both required dependencies and fast-path triggers.\")\n",
    "# await Console(flow3.run_stream(task=\"Process inputs with mixed priority levels.\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e329fe57",
   "metadata": {},
   "source": [
    "### Key Takeaways for Activation Groups\n",
    "\n",
    "1. **`activation_group`**: Groups edges that point to the same target node, allowing you to define different dependency patterns.\n",
    "\n",
    "2. **`activation_condition`**: \n",
    "   - `\"all\"` (default): Target node waits for ALL edges in the group to be satisfied\n",
    "   - `\"any\"`: Target node executes as soon as ANY edge in the group is satisfied\n",
    "\n",
    "3. **Use Cases**:\n",
    "   - **Cycles with multiple entry points**: Different activation groups prevent conflicts\n",
    "   - **Priority-based execution**: Mix \"all\" and \"any\" conditions for different urgency levels  \n",
    "   - **Parallel processing with early termination**: Use \"any\" to proceed with the fastest result\n",
    "\n",
    "4. **Best Practices**:\n",
    "   - Use descriptive group names (`\"critical\"`, `\"optional\"`, `\"feedback\"`, etc.)\n",
    "   - Keep activation conditions consistent within the same group\n",
    "   - Test your graph logic with different execution paths\n",
    "\n",
    "These patterns enable sophisticated workflow control while maintaining clear, understandable execution semantics."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "python",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
